import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // State
  const sidebar = ref({
    opened: true,
    withoutAnimation: false
  })

  const device = ref({
    isMobile: false,
    isTablet: false
  })

  const theme = ref({
    mode: 'light', // 'light' | 'dark'
    primaryColor: '#409EFF',
    size: 'default' // 'large' | 'default' | 'small'
  })

  const settings = ref({
    showSettings: false,
    showTagsView: true,
    showSidebarLogo: true,
    fixedHeader: true,
    sidebarTextTheme: true,
    showFooter: true,
    showBreadcrumb: true,
    showHamburger: true,
    showScreenfull: true,
    showNotification: true,
    showThemeSwitch: true
  })

  const cachedViews = ref([])
  const visitedViews = ref([])

  const loading = ref({
    global: false,
    sidebar: false,
    content: false
  })

  const notification = ref({
    count: 0,
    list: []
  })

  // Computed
  const sidebarOpened = computed(() => sidebar.value.opened)
  const isMobile = computed(() => device.value.isMobile)
  const isTablet = computed(() => device.value.isTablet)
  const isDark = computed(() => theme.value.mode === 'dark')
  const hasNotification = computed(() => notification.value.count > 0)

  // Actions
  const toggleSidebar = (withoutAnimation = false) => {
    sidebar.value.opened = !sidebar.value.opened
    sidebar.value.withoutAnimation = withoutAnimation

    // Save to localStorage
    localStorage.setItem('sidebarOpened', sidebar.value.opened.toString())
  }

  const closeSidebar = (withoutAnimation = false) => {
    sidebar.value.opened = false
    sidebar.value.withoutAnimation = withoutAnimation
    localStorage.setItem('sidebarOpened', 'false')
  }

  const openSidebar = (withoutAnimation = false) => {
    sidebar.value.opened = true
    sidebar.value.withoutAnimation = withoutAnimation
    localStorage.setItem('sidebarOpened', 'true')
  }

  const toggleDevice = deviceType => {
    device.value.isMobile = deviceType === 'mobile'
    device.value.isTablet = deviceType === 'tablet'

    // Auto close sidebar on mobile
    if (device.value.isMobile) {
      closeSidebar(true)
    }
  }

  const setTheme = newTheme => {
    Object.assign(theme.value, newTheme)

    // Apply theme to document
    document.documentElement.setAttribute('data-theme', theme.value.mode)
    document.documentElement.style.setProperty('--el-color-primary', theme.value.primaryColor)

    // Save to localStorage
    localStorage.setItem('theme', JSON.stringify(theme.value))
  }

  const toggleTheme = () => {
    const newMode = theme.value.mode === 'light' ? 'dark' : 'light'
    setTheme({ ...theme.value, mode: newMode })
  }

  const updateSettings = newSettings => {
    Object.assign(settings.value, newSettings)

    // Save to localStorage
    localStorage.setItem('settings', JSON.stringify(settings.value))
  }

  const addCachedView = view => {
    // 安全检查：确保view和view.name存在
    if (!view || !view.name) {
      console.warn('addCachedView: view或view.name为空', view)
      return
    }
    
    // 检查是否已存在
    if (cachedViews.value.includes(view.name)) return
    
    // 安全检查：确保view.meta存在
    if (!view.meta || view.meta.noCache !== true) {
      cachedViews.value.push(view.name)
    }
  }

  const removeCachedView = view => {
    const index = cachedViews.value.indexOf(view.name)
    if (index > -1) {
      cachedViews.value.splice(index, 1)
    }
  }

  const clearCachedViews = () => {
    cachedViews.value = []
  }

  const addVisitedView = view => {
    if (visitedViews.value.some(v => v.path === view.path)) return
    visitedViews.value.push({
      name: view.name,
      path: view.path,
      title: view.meta?.title || 'no-name',
      affix: view.meta?.affix || false
    })
  }

  const removeVisitedView = view => {
    const index = visitedViews.value.findIndex(v => v.path === view.path)
    if (index > -1) {
      visitedViews.value.splice(index, 1)
    }
  }

  const clearVisitedViews = () => {
    visitedViews.value = visitedViews.value.filter(view => view.affix)
  }

  const setLoading = (type, status) => {
    if (Object.prototype.hasOwnProperty.call(loading.value, type)) {
      loading.value[type] = status
    }
  }

  const addNotification = notification => {
    const newNotification = {
      id: Date.now(),
      type: 'info',
      title: '',
      message: '',
      timestamp: new Date(),
      read: false,
      ...notification
    }

    notification.value.list.unshift(newNotification)
    notification.value.count = notification.value.list.filter(n => !n.read).length

    // Auto remove after 5 minutes
    setTimeout(
      () => {
        removeNotification(newNotification.id)
      },
      5 * 60 * 1000
    )
  }

  const removeNotification = id => {
    const index = notification.value.list.findIndex(n => n.id === id)
    if (index > -1) {
      notification.value.list.splice(index, 1)
      notification.value.count = notification.value.list.filter(n => !n.read).length
    }
  }

  const markNotificationAsRead = id => {
    const notificationItem = notification.value.list.find(n => n.id === id)
    if (notificationItem && !notificationItem.read) {
      notificationItem.read = true
      notification.value.count = notification.value.list.filter(n => !n.read).length
    }
  }

  const markAllNotificationsAsRead = () => {
    notification.value.list.forEach(n => {
      n.read = true
    })
    notification.value.count = 0
  }

  const clearAllNotifications = () => {
    notification.value.list = []
    notification.value.count = 0
  }

  const initializeApp = () => {
    // Load from localStorage
    const savedSidebarOpened = localStorage.getItem('sidebarOpened')
    if (savedSidebarOpened !== null) {
      sidebar.value.opened = savedSidebarOpened === 'true'
    }

    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      try {
        const parsedTheme = JSON.parse(savedTheme)
        setTheme(parsedTheme)
      } catch (e) {
        console.warn('Failed to parse saved theme:', e)
      }
    }

    const savedSettings = localStorage.getItem('settings')
    if (savedSettings) {
      try {
        const parsedSettings = JSON.parse(savedSettings)
        updateSettings(parsedSettings)
      } catch (e) {
        console.warn('Failed to parse saved settings:', e)
      }
    }

    // Detect device type
    const userAgent = navigator.userAgent
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
      if (/iPad/i.test(userAgent)) {
        toggleDevice('tablet')
      } else {
        toggleDevice('mobile')
      }
    }

    // Listen for window resize
    const handleResize = () => {
      const width = window.innerWidth
      if (width < 768) {
        toggleDevice('mobile')
      } else if (width < 1024) {
        toggleDevice('tablet')
      } else {
        toggleDevice('desktop')
      }
    }

    window.addEventListener('resize', handleResize)
    handleResize()

    console.log('📱 App store initialized')
  }

  return {
    // State
    sidebar,
    device,
    theme,
    settings,
    cachedViews,
    visitedViews,
    loading,
    notification,

    // Computed
    sidebarOpened,
    isMobile,
    isTablet,
    isDark,
    hasNotification,

    // Actions
    toggleSidebar,
    closeSidebar,
    openSidebar,
    toggleDevice,
    setTheme,
    toggleTheme,
    updateSettings,
    addCachedView,
    removeCachedView,
    clearCachedViews,
    addVisitedView,
    removeVisitedView,
    clearVisitedViews,
    setLoading,
    addNotification,
    removeNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    clearAllNotifications,
    initializeApp
  }
})
